package cn.itcast.web.controller.cargo;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.itcast.domain.vo.ContractProductVo;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.util.DownloadUtils;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping( value ="/cargo/contract", name = "出货表导出")
//出货表,因为要写三种方法所以不写在ContractController购销合同中
public class OutContractController extends BaseController {
    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/print",name = "出货表下载页面")
    public String print(){
        return "cargo/print/contract-print";
    }

    @RequestMapping(value = "/printExcel",name = "excel下载")
    //shipTime船期  与前端jsp的name对应
    public void printExcel(String shipTime) throws Exception {
      List<ContractProductVo> list = contractService.findContractProductVo(getCompanyId(),shipTime);

        ExportParams params = new ExportParams();
        params.setTitle(shipTime.replace("-","年")+"月份出货表");
        Workbook workbook = ExcelExportUtil.exportExcel(params, ContractProductVo.class, list);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        DownloadUtils.download(byteArrayOutputStream,response,"出货表.xlsx");

    }



    @RequestMapping(value = "/printExcelWithTemplate", name = "excel模板下载")
    public void printExcelWithTemplate(String shipTime) throws Exception {
        List<ContractProductVo> list = contractService.findContractProductVo(getCompanyId(), shipTime);
        String realPath = session.getServletContext().getRealPath("make/xlsprint/poi_tempalte.xlsx");
        TemplateExportParams params = new TemplateExportParams(realPath);
        Map map = new HashedMap();
        map.put("title", shipTime.replaceAll("-", "年") + "月份出货表");
        map.put("list", list);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        DownloadUtils.download(byteArrayOutputStream, response, "出货表.xlsx");

    }
}
